package edu.ustb.efws.monitor.controller;

import edu.ustb.efws.base.domain.Detector;
import edu.ustb.efws.base.service.DetectorService;
import edu.ustb.efws.controller.vo.ResultVo;
import edu.ustb.efws.monitor.service.DetectorMonitorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.OptionalLong;
import java.util.stream.Collectors;

@RestController
@RequestMapping("monitor")
@Api(value = "monitor", tags = "M-监测接口")
public class MonitorController {
    private final List<Detector> detectors;
    private final DetectorMonitorService detectorMonitorService;

    @Autowired
    public MonitorController(DetectorService detectorService,
                             DetectorMonitorService detectorMonitorService){

        this.detectors = detectorService.all();
        this.detectorMonitorService = detectorMonitorService;
    }

    @GetMapping(value = "detector", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("监控设备数据采集状态")
    public ResultVo<List<DetectorMonitorVo>> detectorMonitor(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<DetectorMonitorVo> vos = detectors.stream()
                .filter(Detector::getCollect)
                .map(e -> buildDetectorMonitorVo(e, dateFormat))
                .collect(Collectors.toList());

        return ResultVo.success(vos);
    }

    private DetectorMonitorVo buildDetectorMonitorVo(Detector e, DateFormat dateFormat){
        boolean active = detectorMonitorService.isActive(e.getId());
        OptionalLong opt =  detectorMonitorService.getLastTime(e.getId());
        String time = opt.isPresent()? dateFormat.format(new Date(opt.getAsLong())): "--";
        return new DetectorMonitorVo(e, active, time);
    }
}
